package com.example.demo.demos.controller2;

import com.example.demo.demos.domain.User;
import com.example.demo.demos.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/aaa")
public class TestController {
    @Autowired
    private UserService userService;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @GetMapping("/{id}")
    public User getById(@PathVariable Long id){
        return userService.selectById(id);
    }

    @PostMapping("/login")
    public String login(@RequestBody User user, HttpServletResponse response) {
        // 验证用户名密码
        User dbUser = userService.selectByName(user.getName()).get(0);
        if (dbUser != null && dbUser.getPassword().equals(user.getPassword())) {
            // 生成Token（如UUID）
            String token = UUID.randomUUID().toString();

            // 存储到Redis（Key: "login_token_"+token，Value: 用户ID，过期时间7天）
            stringRedisTemplate.opsForValue().set(
                    "login_token123_" + token,
                   dbUser.getId().toString(),
                    7, TimeUnit.DAYS
            );

            // 返回Token到客户端（如Cookie或响应体）
            Cookie cookie = new Cookie("token", token);
            cookie.setMaxAge(7 * 24 * 60 * 60);
            response.addCookie(cookie);
            return "登录成功";
        }
        return "用户名或密码错误";
    }
}
